# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------


import logging
logger = logging.getLogger()

from piHAlibs import (my_fctname,coroutine,db2dict,tstampdev,unitid)
try:
    from .rfxtrxlibs import *
except ImportError as e:
    logger.critical("%s : %s", repr(e.__class__), str(e))
    print ('RFXtrx modules not yet installed')


@my_fctname
@coroutine
def tremdecoder(targets,rejected=None,newids=None,rawevt=None):
    """
    Decoders for X10 RF and ARC / RFXtrx controller
    """
    condition = " WHERE typeunit = 'remote'"
    ids = db2dict('UNITIDS',condition)
    rows = RFXTRXDECODERS
    while True:
        msgs = (yield)
       	logger.debug("Msgs received %s",repr(msgs))
        namedev, type, subtype, data, p, protocol, revt, decrow = msgs
       	logger.debug("Protocol %s type %s subtype %s",protocol, type, subtype)
        if decrow not in rows:
            if rejected: rejected.send(['DECODER_NOT_IMPLEMENTED',protocol] + msgs)
            continue
        row = rows[decrow]
       	try:
       	    res = eval(row[1])
       	except Exception as e:
       	    logger.error("Exception / Error %s",repr(e))
       	    if rejected: rejected.send(['ERR_DECODE',repr(row[1])] + msgs)
       	    continue
       	logger.debug("Result %s",repr(res))
        hu,f,rssi = res[0:3]
        decevt = [protocol,hu,f]
        event = tstampdev(namedev) + ['remote'] + decevt
        for target in targets:
            logger.debug("Function tremdecoder for %s",repr(event))
            target.send(event)
        if rawevt: rawevt.send([namedev,revt] + decevt)
